package com.media.module.utils;

import java.io.InputStream;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;

public class MResource {
	private static final String SRC = "image/";

	/**
	 * 描述：获取src中的图片资源.
	 *
	 * @param src
	 *            图片的src路径，如（“image/arrow.png”）
	 * @return Bitmap 图片
	 */
	public static Drawable getDrawableFromAssets(Context context, String src) {
		Drawable drawable = null;
		try {
			AssetManager assetManager = context.getAssets();
			InputStream is = assetManager.open(SRC + src);
			// bit = BitmapFactory.decodeStream(is);
			drawable = Drawable.createFromStream(is, null);
			drawable = new BitmapDrawable(context.getResources(),
					BitmapFactory.decodeStream(context.getAssets().open(SRC + src)));
		} catch (Exception e) {
			Log.d(MResource.class.getName(), "获取图片异常：" + e.getMessage());
		}
		// BitmapDrawable bd = new BitmapDrawable(context.getResources(), bit);
		return drawable;
	}

	/**
	 * 写入 drawable.addState(new int[]{android.R.attr.state_enabled,
	 * android.R.attr.state_pressed}, mEnabledPressedDrawable);
	 * drawable.addState(new int[0], mDefaultDrawable);
	 * 
	 * @param context
	 * @param strImage
	 *            com/mediarecorder/image/ic_btn_flash_torch_dark_pressed.png
	 * @return
	 */

	public static StateListDrawable getSelectorDrawable(Context context, String[] strImage) {
		StateListDrawable drawable = new StateListDrawable();
		drawable.addState(new int[] { android.R.attr.state_focused }, getDrawableFromAssets(context, strImage[1]));
		drawable.addState(new int[] { android.R.attr.state_enabled, android.R.attr.state_pressed },
				getDrawableFromAssets(context, strImage[1]));
		drawable.addState(new int[] { 0 }, getDrawableFromAssets(context, strImage[0]));
		return drawable;
	}

	/**
	 * TypedValue官方源码中的算法，任意单位转换为PX单位
	 * 
	 * @param unit
	 *            TypedValue.COMPLEX_UNIT_DIP
	 * @param value
	 *            对应单位的值
	 * @param metrics
	 *            密度
	 * @return px值
	 */
	public static float applyDimension(int unit, float value, DisplayMetrics metrics) {
		
		switch (unit) {
		case TypedValue.COMPLEX_UNIT_PX:
			return value;
		case TypedValue.COMPLEX_UNIT_DIP:
			return value * metrics.density;
		case TypedValue.COMPLEX_UNIT_SP:
			return value * metrics.density;
		case TypedValue.COMPLEX_UNIT_PT:
			return value * metrics.xdpi * (1.0f / 72);
		case TypedValue.COMPLEX_UNIT_IN:
			return value * metrics.xdpi;
		case TypedValue.COMPLEX_UNIT_MM:
			return value * metrics.xdpi * (1.0f / 25.4f);
		}
		
		return 0;
	}

}
